package com.itboye.lottery.dialog;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.lottery.R;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.base.BaseDialog;
import com.itboye.lottery.bean.FootballMatchBean;
import com.itboye.lottery.enums.LotteryType;
import com.itboye.lottery.listeners.SelectLisenter;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.itboye.lottery.utils.BetSelectMatches.map;

public class JczqHHDialog extends BaseDialog implements CompoundButton.OnCheckedChangeListener {
    private LotteryType lotteryType;
    private int gPosition;
    private int cPosition;
    Context mContext;
    @BindView(R.id.ll_spf)
    RelativeLayout ll_spf;
    @BindView(R.id.ll_rqspf)
    RelativeLayout ll_rqspf;
    @BindView(R.id.ll_zjq)
    RelativeLayout llZjq;
    @BindView(R.id.ll_bf)
    RelativeLayout ll_bf;
    @BindView(R.id.ll_bqc)
    RelativeLayout llBqc;
    private SelectLisenter selectListener;

    @BindView(R.id.llSPFContainer)
    LinearLayout llSPFContainer;
    @BindView(R.id.llBQCContainer)
    LinearLayout llBQCContainer;
    @BindView(R.id.llZJQContainer)
    LinearLayout llZJQContainer;
    @BindView(R.id.llSFCContainer)
    LinearLayout llSFCContainer;
    @BindView(R.id.llBFContainer)
    LinearLayout llBFContainer;
    @BindView(R.id.homeTeamName)
    TextView homeTeamName;
    @BindView(R.id.awayTeamName)
    TextView awayTeamName;
    @BindView(R.id.tv_spf_txt)
    TextView tv_spf_txt;
    @BindView(R.id.tv_rspf_txt)
    TextView tv_rspf_txt;

    public JczqHHDialog(Context context, ArrayList<FootballMatchBean> footballMatchBeanArrayList, int matchPostion, int cPosition, HashMap<String, Map<String, String>> map, LotteryType lotteryType) {
        super(context);
        this.lotteryType = lotteryType;
        this.gPosition = matchPostion;
        this.cPosition = cPosition;
        this.mContext = context;
        this.footballMatchBeanArrayList = footballMatchBeanArrayList;
        initView();
    }

    public void setSelectListener(SelectLisenter selectListener) {
        this.selectListener = selectListener;
    }

    //red_white_selecter 的边线宽度
    int splitWidth = 0;

    private void initView() {
        setContentView(R.layout.dialog_jczq_hh);
        resetAllViews();
        initTeam();
        splitWidth = ScreenUtil.dpToPx(mContext, 0.5f);
        int height = ScreenUtil.dpToPx(mContext, 40);
        int width = ScreenUtil.getScreenWidth(mContext) - ScreenUtil.dip2px(mContext, 40);
        System.out.println("屏幕寬度：：" + ScreenUtil.getScreenWidth(mContext) + ">>>>>>>." + width);
        int vWidth = 0;
        if (lotteryType == LotteryType.SHOWALL) {
            initShowAllView();
            vWidth = width / 3;
            addSPF(vWidth, height, 3, "0_spf_", ll_spf, 0, footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getHAD());
            addSPF(vWidth, height, 3, "1_rspf_", ll_rqspf, 1, footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getHHAD());
            try {
                tv_spf_txt.setText(footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getHAD().getFixedodds());
            }catch (Exception e){

            }
            try {
                tv_rspf_txt.setText(footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getHHAD().getFixedodds());
            }catch (Exception e){

            }
            vWidth = width / 4;
            addZJQ(vWidth, height, 4);//总进球玩法
            //半全场
            vWidth = width / 3;
            addBQC(vWidth, height, 3);
        } else if (lotteryType == LotteryType.BF) {
            initBFView();
        }
        //比分
        vWidth = width / 5;
        addBF(vWidth, height, 5);

    }

    private void initTeam() {
        homeTeamName.setText(footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getH_cn_abbr());
        awayTeamName.setText(footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getA_cn_abbr());
    }

    private void initBFView() {
        llBFContainer.setVisibility(View.VISIBLE);
    }

    private void initShowAllView() {
        llSPFContainer.setVisibility(View.VISIBLE);
        llBQCContainer.setVisibility(View.VISIBLE);
        llZJQContainer.setVisibility(View.VISIBLE);
        llBFContainer.setVisibility(View.VISIBLE);
//        llSFCContainer.setVisibility(View.VISIBLE);
    }

    private void resetAllViews() {
        llSPFContainer.setVisibility(View.GONE);
        llBQCContainer.setVisibility(View.GONE);
        llZJQContainer.setVisibility(View.GONE);
        llSFCContainer.setVisibility(View.GONE);
        llBFContainer.setVisibility(View.GONE);
        tv_spf_txt.setText("0");
        tv_rspf_txt.setText("0");
    }

    public JczqHHDialog(Context context, boolean fromButton) {
        super(context, fromButton);
    }

    private ArrayList<FootballMatchBean> footballMatchBeanArrayList;


    @OnClick(R.id.tv_cancel)
    void close() {
        dismiss();
    }

    @OnClick(R.id.tv_sure)
    void sure() {
//        Map<String, Map<String, String>> map = new LinkedHashMap<>();
        clearAndBuildData();
        if (this.selectListener != null) {
            this.selectListener.onSelect(footballMatchBeanArrayList, map);
        }
        dismiss();
    }

    private void clearAndBuildData() {
        Map<String, String> spfCd = getCheckData(ll_spf);
        if (spfCd.size() > 0) {
            map.put(gPosition + "_" + cPosition + "_" + "0", spfCd);
        } else {
            map.remove(gPosition + "_" + cPosition + "_" + "0");
        }
        Map<String, String> rspfCd = getCheckData(ll_rqspf);
        if (rspfCd.size() > 0) {
            map.put(gPosition + "_" + cPosition + "_" + "1", rspfCd);
        } else {
            map.remove(gPosition + "_" + cPosition + "_" + "1");
        }
        Map<String, String> zjqCd = getCheckData(llZjq);
        if (zjqCd.size() > 0) {
            map.put(gPosition + "_" + cPosition + "_" + "2", zjqCd);
        } else {
            map.remove(gPosition + "_" + cPosition + "_" + "2");
        }
        Map<String, String> bfCd = getCheckData(ll_bf);
        if (bfCd.size() > 0) {
            map.put(gPosition + "_" + cPosition + "_" + "3", bfCd);
        } else {
            map.remove(gPosition + "_" + cPosition + "_" + "3");
        }
        Map<String, String> bqcCd = getCheckData(llBqc);
        if (bqcCd.size() > 0) {
            map.put(gPosition + "_" + cPosition + "_" + "4", bqcCd);
        } else {
            map.remove(gPosition + "_" + cPosition + "_" + "4");
        }

    }

    private Map<String, String> getCheckData(ViewGroup viewGroup) {
        Map<String, String> list = new HashMap<>();
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            CheckBox checkBox = (CheckBox) viewGroup.getChildAt(i);
            if (checkBox.isChecked()) {
                list.put(checkBox.getTag().toString(), checkBox.getTag().toString());
            }
        }

        return list;
    }

    //胜平负 让球胜平负
    void addSPF(int width, int height, int maxLine, String perfix, ViewGroup view, int dataIndex, FootballMatchBean.MatchInfo.HADBean hadBean) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        for (int i = 0; i < 3; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            StringBuilder str = new StringBuilder();
            boolean isCheck = false;
            boolean isNotSale = false;
            String tagStr = "";
            if (hadBean == null) {
                str.append("未开售");
                isNotSale = true;
            } else {
                switch (i) {
                    case 0://主胜
                        isNotSale = hadBean.getH().isEmpty();
                        tagStr = "主胜_" + hadBean.getH();
                        str.append("胜" + hadBean.getH());
                        break;
                    case 1://平
                        str.append("平" + hadBean.getD());
                        isNotSale = hadBean.getD().isEmpty();
                        tagStr = ("平_" + hadBean.getD());
                        break;
                    case 2://负
                        str.append("负" + hadBean.getA());
                        isNotSale = hadBean.getA().isEmpty();
                        tagStr = ("客胜_" + hadBean.getA());
                        break;
                }
            }
            StringBuilder tag = new StringBuilder();
            tag.append(perfix + i + "_" + tagStr + "_" + (hadBean == null ? "0" : hadBean.getSingle()));
            Log.v("checkBox", "tag dialog" + tag.toString());
            isCheck = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + String.valueOf(dataIndex));
            if (isNotSale) {//isSale为true
                isCheck = false;
            }
            view.addView(createCheckBox(width, height,
                    leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin,
                    str.toString(), tag.toString(), isCheck, 0, "", !isNotSale));
            index++;
        }
    }

    //总进球
    void addZJQ(int width, int height, int maxLine) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        FootballMatchBean.MatchInfo.TTGBean ttgBean = footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getTTG();
        for (int i = 0; i < 8; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            StringBuilder str = new StringBuilder();
            if (i == 7) {
                str.append(i + "+球");
            } else {
                str.append(i + "球");
            }
            str.append("<br/><small><small>");
            boolean isChecked = false;
            String peilv = "";
            switch (i) {
                case 0:
                    str.append(ttgBean.getS0());
                    peilv = ttgBean.getS0();
                    break;
                case 1:
                    str.append(ttgBean.getS1());
                    peilv = ttgBean.getS1();
                    break;
                case 2:
                    str.append(ttgBean.getS2());
                    peilv = ttgBean.getS2();
                    break;
                case 3:
                    str.append(ttgBean.getS3());
                    peilv = ttgBean.getS3();
                    break;
                case 4:
                    str.append(ttgBean.getS4());
                    peilv = ttgBean.getS4();
                    break;
                case 5:
                    str.append(ttgBean.getS5());
                    peilv = ttgBean.getS5();
                    break;
                case 6:
                    str.append(ttgBean.getS6());
                    peilv = ttgBean.getS6();
                    break;
                case 7:
                    str.append(ttgBean.getS7());
                    peilv = ttgBean.getS7();
                    break;
            }
            str.append("</small></small>");
            StringBuilder tag = new StringBuilder();
            tag.append("2_jqs_" + i + "_" + peilv + "_" + i + "_" + (ttgBean == null ? "0" : ttgBean.getSingle()));
            isChecked = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + "2");
            llZjq.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin,
                    str.toString(), tag.toString(), isChecked));
            index++;
        }
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (map.get(index) != null) {
            return map.get(index).get(tag) != null;
        }
        return false;
    }

    //比分
    void addBF(int width, int height, int maxLine) {
        String bf[] = mContext.getResources().getStringArray(R.array.jczq_cbf);
        FootballMatchBean.MatchInfo.CRSBean crsBean = footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getCRS();
        //先将得到的比分实体类转换为KeyMap形式，便于取值
        String[] fieldNames = getFiledName(crsBean.getSpecial_odds());
        Map<String, Double> peiLvMap = new HashMap<>();
        for (String fieldName : fieldNames) {
            //处理属性名称
            //可能是胜平负其他赔率
            if (fieldName.contains("a")) {//主负
                //负其它
                peiLvMap.put("0:9", Double.parseDouble(crsBean.getSpecial_odds().get_$1a()));
            } else if (fieldName.contains("d")) {//平
                peiLvMap.put("9:9", Double.parseDouble(crsBean.getSpecial_odds().get_$1d()));
            } else if (fieldName.contains("h")) {//主胜赔率
                peiLvMap.put("9:0", Double.parseDouble(crsBean.getSpecial_odds().get_$1h()));
            } else {
                String key = addColon(fieldName.substring(2, fieldName.length()));
                double value = Double.parseDouble(getFieldValueByName(fieldName, crsBean.getSpecial_odds()) + "");
                peiLvMap.put(key, value);
            }

        }
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int wm = 0;
        int hm = -splitWidth;
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        boolean br = false;
        int index = 0;
        for (int i = 0; i < bf.length; i++) {
            leftMargin += width;
            wm += ScreenUtil.dpToPx(mContext, 0.5f);
            if (br) {
                //补齐 从头开始排列
                br = false;
                index = 0;
            }
            if (index % maxLine == 0) {
                wm = 0;
                //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                leftMargin = ((maxLine - 1) * splitWidth) / 2;
                topMargin += height;
                hm += splitWidth;
            }
            StringBuilder str = new StringBuilder();
            if (bf[i].equals("9:0")) {
                str.append("胜其它");
                br = true;
            } else if (bf[i].equals("9:9")) {
                str.append("平其它");
            } else if (bf[i].equals("0:9")) {
                str.append("负其它");
            } else {
                str.append(bf[i]);
            }
            StringBuilder tag = new StringBuilder();
            tag.append("3_cbf_" + i + "_" + peiLvMap.get(bf[i]) + "_" + str + "_" + (crsBean == null ? "0" : crsBean.getSingle()));
            tag.append("_" + str.toString() + "_" + bf[i]);
            str.append("<br/><small><small>");
            str.append(peiLvMap.get(bf[i]));
//            str.append(list.get(3)[i]);
            str.append("</small></small>");
            boolean isCheck = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + "3");
            ll_bf.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                    topMargin > 0 ? topMargin - hm : topMargin, str.toString(),
                    tag.toString(), isCheck));
            index++;
        }
    }

    //半全场
    void addBQC(int width, int height, int maxLine) {
        int wm = 0;
        int hm = -splitWidth;
        //因为我从0的时候就+height 所有初始化的时候-height 就刚刚好是0
        int topMargin = -height;
        int leftMargin = ((maxLine - 1) * splitWidth) / 2;
        int index = 0;
        FootballMatchBean.MatchInfo.HAFUBean hafuBean = footballMatchBeanArrayList.get(gPosition).getMatchList().get(cPosition).getHAFU();
        if (hafuBean != null) {
            String keys[] = getFiledName(hafuBean.getSpecial_odds());//change是AS中instant run工具生成出来的，关于instant run的介绍https://segmentfault.com/a/1190000004039742。而serialVersionUID则是序列化验证版本一致性的。//所以使用AS开发中使用发射时最好做一下判断
            for (int i = 0; i < (keys.length > 9 ? 9 : keys.length); i++) {
                String key = keys[i];
                String value = ((getFieldValueByName(key, hafuBean.getSpecial_odds()) + ""));
                leftMargin += width;
                wm += ScreenUtil.dpToPx(mContext, 0.5f);
                if (index % maxLine == 0) {
                    wm = 0;
                    //这里初始化 ((maxLine - 1) * splitWidth) / 2 是由于两个格子都有边框 所有并排在一起的地方会很粗
                    //我就将后一个的位置的边线与前一个重叠 然后重叠出来的空间 分配给整个容器左右两边当间距
                    leftMargin = ((maxLine - 1) * splitWidth) / 2;
                    topMargin += height;
                    hm += splitWidth;
                }
                StringBuilder str = new StringBuilder();
                str.append(key.replaceAll("a", "负").replaceAll("d", "平").replaceAll("h", "胜"));
                StringBuilder tag = new StringBuilder();
                tag.append("4_bqc_" + i + "_" + str.toString() + "_" + value + "_" + (hafuBean == null ? "0" : hafuBean.getSingle()));
                str.append("<br/><small><small>");
                str.append(value);
                str.append("</small></small>");
                boolean isCheck = isCheckThisView(tag.toString(), gPosition + "_" + cPosition + "_" + "4");
                llBqc.addView(createCheckBox(width, height, leftMargin > 0 ? leftMargin - wm : leftMargin,
                        topMargin > 0 ? topMargin - hm : topMargin,
                        str.toString(), tag.toString(), isCheck));
                index++;
            }
        }
    }

    //插入冒号
    private String addColon(String number) {
        if (number == null) {
            return "";
        }
        try {
            int str1 = Integer.parseInt(number.substring(0, 2));
            int str2 = Integer.parseInt(number.substring(2, 4));
            return str1 + ":" + str2;
        } catch (Exception e) {
            return number;
        }
    }

    /**
     * 获取属性名数组
     */
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
//            System.out.println(fields[i].getType());
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /* 根据属性名获取属性值
     * */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            ByAlert.alert(e.getMessage());
            return "0.00";
        }
    }

    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck) {
        return createCheckBox(width, height, leftMargin, topMargin, text, tag, isCheck, -1, "", true);
    }


    CheckBox createCheckBox(int width, int height, int leftMargin, int topMargin, String text, String tag, boolean isCheck, int color, String keyword, boolean isNotSale) {
        CheckBox cb = new CheckBox(mContext);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(width, height);
        rl.leftMargin = leftMargin;
        rl.topMargin = topMargin;
        cb.setLayoutParams(rl);
        cb.setButtonDrawable(R.color.bh);
        cb.setTextColor(ContextCompat.getColorStateList(mContext, R.color.black_white_selector));
        cb.setGravity(Gravity.CENTER);
        cb.setBackgroundResource(R.drawable.red_white_selecter);
        cb.setTag(tag);
        cb.setText(Html.fromHtml(text));
//        cb.setText(StringUtils.matcherSearchText(color, text, keyword));
        cb.setChecked(isCheck);
        cb.setEnabled(isNotSale);
//        cb.setOnCheckedChangeListener(this);
/*       if(type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf") || tag.contains("spf"))) {
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(),R.color.b));
        }*/
//       if(type.equals(JCZQSHOWTYPE.SHOWDG) && (tag.contains("rqspf"))) {
//           //让胜平负是不支持单关的；所以这里我们是需要将其弄成未开售
//            cb.setText("未开售");
//            cb.setEnabled(false);
//            cb.setTextColor(ContextCompat.getColor(getContext(),R.color.b));
//        }
        return cb;
    }

    private boolean isSelectCurrentMatch(String key) {
        boolean hasSelect = false;
        Iterator<String> keySet = map.keySet().iterator();
        while (keySet.hasNext()) {
            String mapKey = keySet.next();
            String str1 = mapKey.split("_")[0];
            String str2 = mapKey.split("_")[1];
            String str3 = mapKey.split("_")[2];
            if (str1.equals(key.split("_")[0]) && str2.equals(key.split("_")[1])) {
                if (str3.equals(key.split("_")[2])) {

                } else {
                    return true;
                }
            }
        }
//        if (map.get(key) != null) {
//            return true;
////            String betType = key.split("_")[2];//投注玩法
////            map
//        }
        Log.v("", "key---" + key);
        return false;
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String keyTemp = compoundButton.getTag() + "";
        String key = keyTemp.substring(0, 1);
        if (isSelectCurrentMatch(gPosition + "_" + cPosition + "_" + key)) {
            compoundButton.setChecked(false);
            ByAlert.alert("一场比赛只能选择一种类型进行投注");
        } else {
            clearAndBuildData();
        }
    }
}
